package com.fm.common.net.baseCoroutine.exception

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.*

/**
 *
 * @Author:         ly2
 * @CreateDate:     2020/12/28
 * @Description:    生命周期控制
 *
 */
class LifeRecycleControl(private val lifecycle: Lifecycle) {
    private var distroyEvent : Lifecycle.Event = Lifecycle.Event.ON_DESTROY

    fun bind(job: Job) {
        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    job.cancelChildren()
                    job.cancel()
                    lifecycle.removeObserver(this)
                }
            }
        })
    }

    fun <T> bind(deferred: Deferred<T>) {
        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    deferred.cancelChildren()
                    deferred.cancel()
                    lifecycle.removeObserver(this)
                }
            }
        })
    }

    fun bind(coroutineScope: CoroutineScope) {
        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    coroutineScope.cancel()
                    lifecycle.removeObserver(this)
                }
            }
        })
    }


}